<template>
  <view class="file-upload-box">
    <view v-if="!readonly" class="file-upload-edit">
      <uni-file-picker file-mediatype="all" v-model="fileList" @delete="handleChange" :limit="limit"></uni-file-picker>
    </view>
    <view class="file-upload-preview">
      <view v-for="(file, idx) in fileList" :key="file.uid" class="file-item flex flex-row align-center">
        <view class="flex-grow-1">
          <view v-if="isImageFile(file.url)">
            <uni-file-picker
              readonly
              :value="[{
                name: file.name,
                url: file.url,
                extname: getFileExtension(file.name)
              }]"
              :imageStyles="imageStyles"
              file-mediatype="image"
            />
          </view>
          <view v-else>{{ file.name }}</view>
        </view>
        <view class="file-download flex-shrink-0">
          <uni-icons class="icon-download" type="download" color="#000" size="48rpx" @click="handleDownload(file)"></uni-icons>
          <uni-icons v-if="!readonly" class="icon-close" type="close" color="#000" size="48rpx" @click="handleRemove(idx)"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {downloadAndOpenFile, downloadFile, getFileExtension, isImageFile, webDownloadFile} from "@/utils/file";

defineOptions({ name: 'PmFileUpload' });

const $emit = defineEmits(["update:files"]);
const props = defineProps({
  files: {
    type: [String, Array<PmFileForm>],
    default: null,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 99,
  },
  fileType: {
    type: Array<string>,
    default: null,
  }
})

const fileList = ref<Array<PmFileForm>>([]);
watch(() => props.files, () =>{
  if (props.files) {
    if (Array.isArray(props.files)) {
      fileList.value = props.files;
    } else {
      try {
        if (props.files === '' || props.files === '[]') {
          fileList.value = null;
          return;
        }
        const newFiles = JSON.parse(props.files) as unknown as Array<PmFileForm>;
        if (newFiles.length > 0) {
          fileList.value = newFiles
        }
      } catch (e: any) {
        new Error(e);
      }
    }
  }
}, {immediate: true});

function handleChange() {
  const newFiles = toRaw(fileList.value)
  if (newFiles && newFiles.length > 0) {
    $emit('update:files', JSON.stringify(newFiles));
  } else {
    $emit('update:files', null);
  }
}

function handleRemove(idx: number) {
  const newList = [...fileList.value];
  uni.showModal({
    title: '提示',
    content: `是否删除【${newList[idx].name}】`,
    success: (res) => {
      if (res.confirm) {
        newList.splice(idx, 1);
        if (newList && newList.length > 0) {
          $emit('update:files', JSON.stringify(newList));
        } else {
          $emit('update:files', null);
        }
      }
    },
    fail: () => {},
  })
}

function handleDownload(file: PmFileForm) {
  // #ifdef H5
  webDownloadFile(file.url, file.name);
  // #endif
  // #ifdef APP-PLUS
  downloadAndOpenFile(file.url)
  // #endif
}

const imageStyles = {
  width: 64,
  height: 64,
  // border: {
  //   radius: '50%'
  // }
}
const listStyles = {
  // 是否显示边框
  border: true,
  // 是否显示分隔线
  dividline: true,
  // 线条样式
  borderStyle: {
    width: '2rpx',
    color: 'blue',
    style: 'dashed',
    radius: '2',
  }
}
</script>

<style scoped lang="scss">
.file-image {
  width: 128rpx;
  height: 128rpx;
}

.file-upload-preview {
  .file-item {
    position: relative;
    line-height: 64rpx;
    border: 2rpx #409eff dashed;
    margin-bottom: 8px;
    padding: 10rpx 20rpx;
  }
}

.file-download {
  .icon-close {
    margin-left: 20rpx;
  }
}

:deep(.uni-file-picker__lists) {
  display: none;
}
</style>
